package com.yummy.cloud.gateway.loadbalancer;

import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Service;

import com.yummy.cloud.gateway.manage.dao.mapper.LoadBalancerConfigMapper;
import com.yummy.cloud.gateway.manage.dao.model.LoadBalancerConfig;

@Service
public class LoadBalancerRepository {
	
	@Autowired
	private LoadBalancerConfigMapper loadBalancerConfigMapper;

	public List<ServiceInstance> getInstances(String serviceId) {
		LoadBalancerConfig config = loadBalancerConfigMapper.selectByPrimaryKey(serviceId);
		if(config == null) {
			return Collections.emptyList();
		}
		List<ServiceInstance> serviceInstances = getServiceInstances(config);
		return serviceInstances;
	}

	private List<ServiceInstance> getServiceInstances(LoadBalancerConfig config) {
		if(StringUtils.isEmpty(config.getServiceInstances())){
			return Collections.emptyList();
		}
		String[] array = config.getServiceInstances().split(",");
		return Stream.of(array).map(s -> {
			URI uri = URI.create(s);
			DefaultServiceInstance ins = new DefaultServiceInstance();
			ins.setServiceId(config.getId());
			ins.setUri(uri);
			ins.setInstanceId("");
			return ins;
		}).collect(Collectors.toList());
	}

	public List<String> getServices() {
		List<String> list = loadBalancerConfigMapper.selectIds();
		if(list == null) {
			return Collections.emptyList();
		}
		return list;
	}

}
